import errorCodesBuilder from '../helpers/errorCodesBuilder';

const errorCodes = errorCodesBuilder('用户同意认证时间更新失败');

export default server => {
	const {
		app: { schemaComposer },
	} = server;

	schemaComposer.Mutation.addFields({
		UpdateAgreeTime: {
			description: '记录用户同意条款时间',
			type: 'User',
			async resolve(root, params, { request }) {
				const {
					server: {
						app: {
							model: { User },
						},
					},
					auth: {
						credentials: { uid },
					},
				} = request;

				const user = await User.findById(uid);
				if (user) {
					user.disclaimerAgreeTime = new Date();
				}
				try {
					await user.save();
				} catch (err) {
					const error = errorCodes['[03]更新用户同意免责条款时间失败'].from(
						err
					);
					server.log.error({ error }, error.rawMessage);
					throw error;
				}

				return user;
			},
		},
	});
};
